import edge_tts
import sys
import os

text = sys.argv[1]
voice = sys.argv[2]
volume = sys.argv[3]
rate = sys.argv[4]
taskId = sys.argv[5]
fileName = "speech"
OUTPUT_FOLDER = f"./output/{taskId}"
OUTPUT_FILE = f"{OUTPUT_FOLDER}/{fileName}.mp3"
WEBVTT_FILE = f"{OUTPUT_FOLDER}/{fileName}.vtt"
communicate = edge_tts.Communicate(text=text, voice=voice, rate=rate, volume=volume)
submaker = edge_tts.SubMaker()

os.makedirs(OUTPUT_FOLDER, exist_ok=True)

with open(OUTPUT_FILE, "wb") as file:
    for chunk in communicate.stream_sync():
        if chunk["type"] == "audio":
            file.write(chunk["data"])
        elif chunk["type"] == "WordBoundary":
            submaker.create_sub((chunk["offset"], chunk["duration"]), chunk["text"])

with open(WEBVTT_FILE, "w", encoding="utf-8") as file:
    file.write(submaker.generate_subs())